#include "clientserver.h"
#include "../common/comiocontroller.h"
ClientServer::ClientServer(QObject *parent) :
    QObject(parent)
{
    m_iTimeOutMS = 6000;
    m_ready = false;
    m_iPort = 0;


    connect(&m_server, SIGNAL(connected()), SLOT(slot_connected()));
    connect(&m_server, SIGNAL(disconnected()), SLOT(slot_disconnected()));
    connect(&m_server, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(slot_error(QAbstractSocket::SocketError)));

}

ClientServer::~ClientServer()
{
    disconnectFromServer();
}



bool ClientServer::connectToServer(QString cStrIp, int iPort)
{
    this->m_cStrIp = cStrIp;
    this->m_iPort = iPort;
    m_server.connectToHost(m_cStrIp, iPort);
    if( m_server.waitForConnected(m_iTimeOutMS) == false ) {
        ComIOController::getInstance()->msgOutput(QString("<ClientServer::connectToServer>:") + m_server.errorString(), MSG_ERROR);
        return false;
    }else{
        return true;
    }
}

bool ClientServer::disconnectFromServer()
{
    //synchronous
    m_server.disconnectFromHost();
    if( m_server.waitForDisconnected(m_iTimeOutMS) ) {
        ComIOController::getInstance()->msgOutput(QString("<ClientServer::disconnectFromServer>:") + m_server.errorString(), MSG_ERROR);
        return false;
    }else{
        return true;
    }
}

bool ClientServer::reconnect()
{
    return this->connectToServer(m_cStrIp, m_iPort);
}

void ClientServer::slot_connected()
{
    ComIOController::getInstance()->msgOutput(QString("<ClientServer::slot_connected>:Server connected."));

    m_ready = true;
    emit sig_connected();
}

void ClientServer::slot_disconnected()
{
    ComIOController::getInstance()->msgOutput(QString("<ClientServer::slot_disconnected>:Server disconnected."));
    m_ready = false;
    emit sig_disconnected();
}

void ClientServer::slot_error(QAbstractSocket::SocketError socketError)
{
    ComIOController::getInstance()->msgOutput(QString("<ClientServer::slot_error>:Socket error occured, ") + m_server.errorString(), MSG_ERROR);

}
